<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./vue.js"></script>
    <style>
        .select{
            background: #ccc;
        }
    </style>
</head>
<body>

    <!-- 定义挂载点 -->
    <div id="app">
        <input type="text" v-model="kw" @keydown.down="down" @keydown.up="up" @keydown.enter="enter">
        <ul>
            <!-- 5.遍历数据 -->
            <li v-for="(item,index) in arr" :key="item" v-if="index < 4" :class="n==index ? 'select':''">{{item}}</li>
        </ul>
    </div>

    <script>
        /* 
        jsonp原理：
          1.创建一个script标签 let os = doucment.createElement("script");
          2.添加src属性  os.src = "url?cb=aa"
          3.添加到页面  document.body.appendChild(os)
        */
        let vm = new Vue({
            //挂载点
            el:"#app",
            //数据
            data:{
                //1.初始化数据
                kw:"", //关键字
                arr:[], //数据
                n:-1,
            },
            //方法
            methods:{
                //5.down
                down(){
                    this.n++;
                    if(this.n >= 4){
                        this.n = -1;
                    }
                },
                //6.up
                up(){
                    this.n--;
                    if(this.n <= -1){
                        this.n = 4;
                    }
                },
                enter(){
                    window.open('https://www.baidu.com/s?wd='+this.arr[this.n],'_self');
                }
            },
            watch:{
                //2.监听数据的变化
                kw(){
                    if(this.kw == ""){
                        this.arr = [];
                        return;
                    }

                    //3.jsonp发请求
                    let os = document.createElement("script");
                    os.src = 'http://suggestion.baidu.com/su?cb=aa&wd='+this.kw;
                    document.body.appendChild(os)
                }
            }
        })

        //4.回调函数处理数据
        function aa(res){
           vm.arr = res.s;
        }
    </script>
</body>
</html>


